/**
 * 
 */
package com.verisette.framework.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import org.corp.agi.common.bean.Message;
import org.corp.agi.web.action.BaseAction;
import org.corp.agi.web.constant.WebConstant;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;

/**
 * {Description here}
 *
 * @author Pongsatorn Paolanwat (Mix)
 * @since Mar 10, 2010 6:29:30 PM
 * @see 
 */
public class CustomMessageInterceptor  extends AbstractInterceptor implements PreResultListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8957122520779116962L;

	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(CustomMessageInterceptor.class);
	
	
//	public void destroy() {
//		
//	}
	
//	public void init() {
//		
//	}
	
	public String intercept(ActionInvocation invocation) throws Exception {
		invocation.addPreResultListener(this);
		return invocation.invoke();
	}

	public void beforeResult(ActionInvocation invocation, String resultCode) {
		
		HttpServletRequest httpServletRequest = ServletActionContext.getRequest();
		HttpSession httpSession = httpServletRequest.getSession();
		
		if( httpServletRequest.isRequestedSessionIdValid() ) {
			if( httpSession.getAttribute( WebConstant.SESSION_STATUS_KEY ) == null ) {
				if( ((BaseAction)invocation.getAction()).getStatus() != null ) {
					List<Message> list = ((BaseAction)invocation.getAction()).getMessageList();
					StringBuilder sb = new StringBuilder();
					for (Message message : list) {
						sb.append(message.getMessageCode());
						sb.append(" : ");
						sb.append(message.getMessageText());
						//sb.append("\n");
					}
					httpSession.setAttribute(WebConstant.SESSION_MESSAGE_KEY, sb.toString());
					httpSession.setAttribute(WebConstant.SESSION_STATUS_KEY, ((BaseAction)invocation.getAction()).getStatus());
					
					if (logger.isDebugEnabled()) {
						logger.debug(((BaseAction)invocation.getAction()).getStatus()+":"+sb.toString());
					}
				}
			}
		}
	}

}
